#import sqlite3
#from tabnanny import check
import time
import argparse
from flask import Flask, request, jsonify, render_template

timestamp_ms = int(time.time() * 1000)
t = timestamp_ms
app = Flask(__name__)
# 在文件顶部添加导入
import sqlite3
#from sqlite3 import Connection
#from pysqlcipher3 import dbapi2 as sqlcipher

def init_db(dbname:str,type_:str,id_xue:int):
    """初始化加密数据库"""
    if str(type)!='0':
        key = str(id_xue)[:5]  # 替换为你的加密密钥
        #conn = sqlcipher.connect(dbname)
        conn = sqlite3.connect(dbname)
        cursor = conn.cursor()
        cursor.execute(f"PRAGMA key='{key}'")
    else:
        conn = sqlite3.connect(dbname)
        cursor = conn.cursor()
    # 创建用户表
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL,
        password TEXT NOT NULL,
        email TEXT,
        is_admin INTEGER DEFAULT 0
    )
    ''')

    # 插入一些测试数据
    cursor.execute("SELECT COUNT(*) FROM users")
    if cursor.fetchone()[0] == 0:
        test_users = [
            ('admin', 'angong2400', 'admin@qq.com', 1),
            ('alice', 'alicepass', 'alice@fox.com', 0),
            ('bob', 'bobpass', 'bob@gmail.com', 0),
            ('test', 'test123', 'test@example.com', 0)
        ]
        cursor.executemany(
            "INSERT INTO users (username, password, email, is_admin) VALUES (?, ?, ?, ?)",
            test_users
        )

    conn.commit()
    conn.close()


@app.route('/')
def index():
    """主页，显示简单的使用说明"""
    return render_template('index.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    """登录接口，存在SQL注入漏洞"""
    if request.method == 'GET':
        return render_template('login.html')

    username = request.form.get('username', '')
    password = request.form.get('password', '')

    conn = sqlite3.connect(DATABASE)
    cursor = conn.cursor()

    # 故意构造不安全的SQL查询，用于测试SQL注入
    query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
    print(f"执行的SQL: {query}")  # 用于调试

    try:
        cursor.execute(query)
        user = cursor.fetchone()
    except sqlite3.Error as e:
        return jsonify({
            'status': 'error',
            'message': f'SQL错误: {str(e)}'
        })

    conn.close()

    if user:
        return jsonify({
            'status': 'success',
            'message': '登录成功',
            'user': {
                'id': user[0],
                'username': user[1],
                'email': user[3],
                'is_admin': bool(user[4])
            }
        })
    else:
        return jsonify({
            'status': 'fail',
            'message': '用户名或密码错误'
        })


@app.route('/safe_login', methods=['POST'])
def safe_login():
    """安全的登录接口，使用参数化查询"""
    username = request.form.get('username', '')
    password = request.form.get('password', '')

    conn = sqlite3.connect(DATABASE)
    cursor = conn.cursor()

    # 使用参数化查询防止SQL注入
    query = "SELECT * FROM users WHERE username=? AND password=?"
    cursor.execute(query, (username, password))
    user = cursor.fetchone()
    conn.close()

    if user:
        return jsonify({
            'status': 'success',
            'message': '登录成功',
            'user': {
                'id': user[0],
                'username': user[1],
                'email': user[3],
                'is_admin': bool(user[4])
            }
        })
    else:
        return jsonify({
            'status': 'fail',
            'message': '用户名或密码错误'
        })


@app.route('/search', methods=['GET', 'POST'])
def search():
    """搜索接口，存在SQL注入漏洞"""
    if request.method == 'GET':
        return render_template('search.html')

    search_term = request.form.get('search_term', '')

    conn = sqlite3.connect(DATABASE)
    cursor = conn.cursor()

    # 不安全的查询，用于测试
    query = f"SELECT id, username, email FROM users WHERE username LIKE '%{search_term}%' OR email LIKE '%{search_term}%'"
    print(f"执行的SQL: {query}")  # 用于调试

    try:
        cursor.execute(query)
        results = cursor.fetchall()
    except sqlite3.Error as e:
        return jsonify({
            'status': 'error',
            'message': f'SQL错误: {str(e)}'
        })

    conn.close()

    return jsonify({
        'status': 'success',
        'results': [{
            'id': row[0],
            'username': row[1],
            'email': row[2]
        } for row in results]
    })

def check_(x):
    """检查学号是否为11位数字"""
    if not isinstance(x, str):  # 确保输入是字符串
        x = str(x)
    if len(x) != 11 or not x.isdigit():  # 检查长度和是否为纯数字
        raise ValueError('请输入11位数字的学号')
if __name__ == '__main__':
    argparse = argparse.ArgumentParser()
    argparse.add_argument('--type',type=int,default=0,help="有练习版本 输入'0' 和 考试版本 输入‘1’，当前版本的软件仅支持练习版")
    argparse.add_argument('--id', type=int,default=20403000609,help='初始化数据库,请输入你的学号')
    args = argparse.parse_args()

    DATABASE = f'{bin(t)[:8]}.db'
    check_(str(args.id))
    id_xuehao=int(args.id)# 直接传递字符串参数
    init_db(DATABASE,args.type,id_xuehao)
    app.run(debug=True, port=5000)
    #提示：python app.py然后去登录浏览器 127.0.0.1:5000